import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/collect.dart';
import '../services/api_service.dart';
import '../constants/app_constants.dart';
import 'add_collection_page.dart';

class CollectionDetailPage extends StatefulWidget {
  final List<CollectionItem> items;
  final int initialIndex;

  const CollectionDetailPage({
    super.key,
    required this.items,
    required this.initialIndex,
  });

  @override
  State<CollectionDetailPage> createState() => _CollectionDetailPageState();
}

class _CollectionDetailPageState extends State<CollectionDetailPage> {
  late PageController _pageController;
  late int _currentIndex;
  final Map<int, _PageState> _pageStates = {};
  PreviewStyle _globalPreviewStyle = PreviewStyle.quote;
  static const String _previewStyleKey = 'preview_style';

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: widget.initialIndex);
    _loadPreviewStyle();
  }

  Future<void> _loadPreviewStyle() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final styleIndex = prefs.getInt(_previewStyleKey);
      if (styleIndex != null && styleIndex < PreviewStyle.values.length) {
        setState(() {
          _globalPreviewStyle = PreviewStyle.values[styleIndex];
        });
      }
    } catch (e) {
      print('加载预览样式失败: $e');
    }
  }

  Future<void> _savePreviewStyle(PreviewStyle style) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt(_previewStyleKey, style.index);
    } catch (e) {
      print('保存预览样式失败: $e');
    }
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  _PageState _getPageState(int index) {
    if (!_pageStates.containsKey(index)) {
      final item = widget.items[index];
      final extractedUrl = _extractUrl(item.content);

      WebViewController? webViewController;
      if (extractedUrl != null) {
        webViewController = WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onPageFinished: (String url) {
                if (_pageStates.containsKey(index)) {
                  setState(() {
                    _pageStates[index]!.isLoading = false;
                  });
                }
              },
            ),
          )
          ..loadRequest(Uri.parse(extractedUrl));
      }

      // 根据 showType 决定初始展示模式
      // showType: 0=预览, 1=原文
      // 注意：showWebView 的命名有误导性，实际逻辑是：
      // - showWebView = true: 显示预览样式（菜单显示"原文"表示可以切换）
      // - showWebView = false: 显示原文内容（菜单显示"预览"表示可以切换）
      final bool initialShowWebView = item.showType == 0;

      _pageStates[index] = _PageState(
        extractedUrl: extractedUrl,
        webViewController: webViewController,
        isLoading: extractedUrl != null,
        showWebView: initialShowWebView,
      );
    }
    return _pageStates[index]!;
  }

  /// 从文本中提取URL
  String? _extractUrl(String text) {
    final urlPattern = RegExp(
      r'https?://[^\s<>"]+',
      caseSensitive: false,
    );
    final match = urlPattern.firstMatch(text);
    return match?.group(0);
  }

  void _onEdit(BuildContext context, CollectionItem item) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AddCollectionPage(
          editItem: item,
        ),
      ),
    );
  }

  Future<void> _onToggleFavorite(BuildContext context, CollectionItem item) async {
    try {
      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );

      await ApiService.updateFavoriteStatus(
        id: item.id,
        isFavorite: !item.isFavorite,
      );

      if (context.mounted) {
        Navigator.pop(context); // 关闭加载对话框

        // 更新列表中的item状态
        final index = widget.items.indexWhere((i) => i.id == item.id);
        if (index != -1) {
          widget.items[index] = CollectionItem(
            id: item.id,
            title: item.title,
            content: item.content,
            discuss: item.discuss,
            source: item.source,
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            tags: item.tags,
            isFavorite: !item.isFavorite,
            showType: item.showType,
          );
        }

        setState(() {}); // 刷新UI

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(item.isFavorite ? '已取消喜欢' : '已添加到喜欢'),
          ),
        );
      }
    } catch (e) {
      if (context.mounted) {
        Navigator.pop(context); // 关闭加载对话框
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('操作失败: $e')),
        );
      }
    }
  }

  Future<void> _updateShowType(String id, int showType) async {
    try {
      await ApiService.updateShowType(
        id: id,
        showType: showType,
      );

      // 更新列表中的item状态
      final index = widget.items.indexWhere((i) => i.id == id);
      if (index != -1) {
        final item = widget.items[index];
        widget.items[index] = CollectionItem(
          id: item.id,
          title: item.title,
          content: item.content,
          discuss: item.discuss,
          source: item.source,
          categoryId: item.categoryId,
          categoryName: item.categoryName,
          tags: item.tags,
          isFavorite: item.isFavorite,
          showType: showType,
        );
      }
    } catch (e) {
      print('更新展示类型失败: $e');
      // 静默失败，不影响用户体验
    }
  }

  Future<void> _onDelete(BuildContext context, CollectionItem item) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这条收藏吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true && context.mounted) {
      try {
        // 显示加载提示
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => const Center(
            child: CircularProgressIndicator(),
          ),
        );

        await ApiService.deleteCollection(item.id);

        if (context.mounted) {
          Navigator.pop(context); // 关闭加载对话框
          Navigator.pop(context, true); // 返回上一页，传递true表示已删除
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('删除成功')),
          );
        }
      } catch (e) {
        if (context.mounted) {
          Navigator.pop(context); // 关闭加载对话框
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('删除失败: $e')),
          );
        }
      }
    }
  }

  // 效果1：引号式
  Widget _buildQuotePreview(CollectionItem item) {
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 48),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          if (item.categoryName.isNotEmpty) ...[
            Align(
              alignment: Alignment.centerLeft,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.primaryContainer,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  item.categoryName,
                  style: TextStyle(
                    fontSize: 13,
                    color: Theme.of(context).colorScheme.onPrimaryContainer,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
            const SizedBox(height: 40),
          ],
          Text(
            '"',
            style: TextStyle(
              fontSize: 64,
              height: 0.5,
              color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          if (item.content.isNotEmpty)
            Text(
              item.content,
              style: TextStyle(
              fontSize: 20,
              height: 2.0,
              color: Theme.of(context).brightness == Brightness.light
                  ? Colors.black87
                  : Colors.white.withOpacity(0.87),
              letterSpacing: 0.5,
            ),
            textAlign: TextAlign.justify,
          ),
          const SizedBox(height: 8),
          Align(
            alignment: Alignment.centerRight,
            child: Text(
              '"',
              style: TextStyle(
                fontSize: 64,
                height: 0.5,
                color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          if (item.discuss.isNotEmpty) ...[
            const SizedBox(height: 24),
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.light
                    ? Colors.grey[100]
                    : Colors.grey[800],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Text(
                item.discuss,
                style: TextStyle(
                  fontSize: 16,
                  height: 1.6,
                  color: Theme.of(context).brightness == Brightness.light
                      ? Colors.black87
                      : Colors.white.withOpacity(0.87),
                  fontStyle: FontStyle.italic,
                ),
                textAlign: TextAlign.left,
              ),
            ),
          ],
          if (item.source.isNotEmpty) ...[
            const SizedBox(height: 32),
            Align(
              alignment: Alignment.centerRight,
              child: Text(
                '—— ${item.source}',
                style: TextStyle(
                  fontSize: 16,
                  color: Theme.of(context).brightness == Brightness.light
                      ? Colors.grey[600]
                      : Colors.grey[400],
                  fontStyle: FontStyle.italic,
                  letterSpacing: 0.3,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 效果2：卡片式
  Widget _buildCardPreview(CollectionItem item) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(24),
      child: Column(
        children: [
          if (item.categoryName.isNotEmpty) ...[
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                item.categoryName,
                style: TextStyle(
                  fontSize: 13,
                  color: Theme.of(context).colorScheme.onPrimaryContainer,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            const SizedBox(height: 24),
          ],
          Container(
            padding: const EdgeInsets.all(32),
            decoration: BoxDecoration(
              color: Theme.of(context).brightness == Brightness.light
                  ? Colors.amber[50]
                  : Colors.grey[850],
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Column(
              children: [
                if (item.content.isNotEmpty)
                  Text(
                    item.content,
                    style: TextStyle(
                    fontSize: 22,
                    height: 1.8,
                    color: Theme.of(context).brightness == Brightness.light
                        ? Colors.black87
                        : Colors.white.withOpacity(0.87),
                    letterSpacing: 0.3,
                  ),
                  textAlign: TextAlign.center,
                ),
                if (item.discuss.isNotEmpty) ...[
                  const SizedBox(height: 20),
                  Divider(color: Colors.grey[400]),
                  const SizedBox(height: 12),
                  Text(
                    item.discuss,
                    style: TextStyle(
                      fontSize: 16,
                      height: 1.6,
                      color: Theme.of(context).brightness == Brightness.light
                          ? Colors.black87
                          : Colors.white.withOpacity(0.87),
                      fontStyle: FontStyle.italic,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
                if (item.source.isNotEmpty) ...[
                  const SizedBox(height: 24),
                  Text(
                    '—— ${item.source}',
                    style: TextStyle(
                      fontSize: 16,
                      color: Theme.of(context).brightness == Brightness.light
                          ? Colors.grey[700]
                          : Colors.grey[400],
                      fontStyle: FontStyle.italic,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 效果3：简约式
  Widget _buildMinimalPreview(CollectionItem item) {
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 40, vertical: 60),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          if (item.categoryName.isNotEmpty) ...[
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                item.categoryName,
                style: TextStyle(
                  fontSize: 13,
                  color: Theme.of(context).colorScheme.onPrimaryContainer,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            const SizedBox(height: 50),
          ],
          if (item.content.isNotEmpty)
            Text(
              item.content,
              style: TextStyle(
              fontSize: 24,
              height: 2.0,
              color: Theme.of(context).brightness == Brightness.light
                  ? Colors.black87
                  : Colors.white.withOpacity(0.87),
              letterSpacing: 1.0,
              fontWeight: FontWeight.w300,
            ),
            textAlign: TextAlign.center,
          ),
          if (item.discuss.isNotEmpty) ...[
            const SizedBox(height: 32),
            Text(
              item.discuss,
              style: TextStyle(
                fontSize: 16,
                height: 1.8,
                color: Theme.of(context).brightness == Brightness.light
                    ? Colors.grey[700]
                    : Colors.grey[400],
                letterSpacing: 0.5,
                fontStyle: FontStyle.italic,
              ),
              textAlign: TextAlign.center,
            ),
          ],
          if (item.source.isNotEmpty) ...[
            const SizedBox(height: 40),
            Text(
              item.source,
              style: TextStyle(
                fontSize: 14,
                color: Theme.of(context).brightness == Brightness.light
                    ? Colors.grey[500]
                    : Colors.grey[500],
                letterSpacing: 2.0,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ],
      ),
    );
  }

  // 效果4：书签式
  Widget _buildBookmarkPreview(CollectionItem item) {
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 40),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 6,
            height: 200,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Theme.of(context).colorScheme.primary,
                  Theme.of(context).colorScheme.primary.withOpacity(0.3),
                ],
              ),
              borderRadius: BorderRadius.circular(3),
            ),
          ),
          const SizedBox(width: 24),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (item.categoryName.isNotEmpty) ...[
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primaryContainer,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      item.categoryName,
                      style: TextStyle(
                        fontSize: 13,
                        color: Theme.of(context).colorScheme.onPrimaryContainer,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                ],
                if (item.content.isNotEmpty)
                  Text(
                    item.content,
                    style: TextStyle(
                    fontSize: 20,
                    height: 1.8,
                    color: Theme.of(context).brightness == Brightness.light
                        ? Colors.black87
                        : Colors.white.withOpacity(0.87),
                    letterSpacing: 0.5,
                  ),
                  textAlign: TextAlign.left,
                ),
                if (item.discuss.isNotEmpty) ...[
                  const SizedBox(height: 20),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Theme.of(context).brightness == Brightness.light
                          ? Colors.grey[100]
                          : Colors.grey[800],
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      item.discuss,
                      style: TextStyle(
                        fontSize: 16,
                        height: 1.6,
                        color: Theme.of(context).brightness == Brightness.light
                            ? Colors.black87
                            : Colors.white.withOpacity(0.87),
                        fontStyle: FontStyle.italic,
                      ),
                      textAlign: TextAlign.left,
                    ),
                  ),
                ],
                if (item.source.isNotEmpty) ...[
                  const SizedBox(height: 24),
                  Text(
                    '—— ${item.source}',
                    style: TextStyle(
                      fontSize: 15,
                      color: Theme.of(context).brightness == Brightness.light
                          ? Colors.grey[600]
                          : Colors.grey[400],
                      fontStyle: FontStyle.italic,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  // 效果5：渐变式
  Widget _buildGradientPreview(CollectionItem item) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: Theme.of(context).brightness == Brightness.light
              ? [
                  Theme.of(context).colorScheme.primary.withOpacity(0.1),
                  Theme.of(context).colorScheme.secondary.withOpacity(0.1),
                ]
              : [
                  Theme.of(context).colorScheme.primary.withOpacity(0.2),
                  Theme.of(context).colorScheme.secondary.withOpacity(0.2),
                ],
        ),
      ),
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(32),
        child: Column(
          children: [
            if (item.categoryName.isNotEmpty) ...[
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(12),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                child: Text(
                  item.categoryName,
                  style: TextStyle(
                    fontSize: 13,
                    color: Theme.of(context).colorScheme.primary,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              const SizedBox(height: 40),
            ],
            Container(
              padding: const EdgeInsets.all(28),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.9),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20,
                    offset: const Offset(0, 10),
                  ),
                ],
              ),
              child: Column(
                children: [
                  if (item.content.isNotEmpty)
                    Text(
                      item.content,
                      style: const TextStyle(
                      fontSize: 21,
                      height: 1.9,
                      color: Colors.black87,
                      letterSpacing: 0.4,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  if (item.discuss.isNotEmpty) ...[
                    const SizedBox(height: 20),
                    Divider(color: Colors.grey[400]),
                    const SizedBox(height: 16),
                    Text(
                      item.discuss,
                      style: TextStyle(
                        fontSize: 16,
                        height: 1.6,
                        color: Colors.grey[800],
                        fontStyle: FontStyle.italic,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                  if (item.source.isNotEmpty) ...[
                    const SizedBox(height: 24),
                    Text(
                      '—— ${item.source}',
                      style: TextStyle(
                        fontSize: 15,
                        color: Colors.grey[700],
                        fontStyle: FontStyle.italic,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBody(CollectionItem item, _PageState pageState) {
    // 如果有URL且显示WebView模式
    if (pageState.extractedUrl != null && pageState.webViewController != null && pageState.showWebView) {
      return Stack(
        children: [
          WebViewWidget(controller: pageState.webViewController!),
          if (pageState.isLoading)
            const Center(
              child: CircularProgressIndicator(),
            ),
        ],
      );
    }

    // 原文模式
    if (!pageState.showWebView) {
      return SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (item.categoryName.isNotEmpty) ...[
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 6,
                ),
                decoration: BoxDecoration(
                  color: Colors.blue[100],
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  item.categoryName,
                  style: TextStyle(
                    fontSize: 13,
                    color: Colors.blue[800],
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              const SizedBox(height: 12),
            ],
            if (item.source.isNotEmpty) ...[
              Text(
                '出处：${item.source}',
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.grey[600],
                  fontStyle: FontStyle.italic,
                ),
              ),
              const SizedBox(height: 12),
            ],
            if (item.content.isNotEmpty)
              Text(
                item.content,
                style: const TextStyle(
                  fontSize: 16,
                  height: 1.5,
                ),
              ),
            if (item.discuss.isNotEmpty) ...[
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Theme.of(context).brightness == Brightness.light
                      ? Colors.grey[100]
                      : Colors.grey[800],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '评论：',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      item.discuss,
                      style: const TextStyle(
                        fontSize: 16,
                        height: 1.5,
                        fontStyle: FontStyle.italic,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
      );
    }

    // 预览模式（没有URL的纯文字预览）
    switch (_globalPreviewStyle) {
      case PreviewStyle.quote:
        return _buildQuotePreview(item);
      case PreviewStyle.card:
        return _buildCardPreview(item);
      case PreviewStyle.minimal:
        return _buildMinimalPreview(item);
      case PreviewStyle.bookmark:
        return _buildBookmarkPreview(item);
      case PreviewStyle.gradient:
        return _buildGradientPreview(item);
    }
  }

  @override
  Widget build(BuildContext context) {
    // 安全检查：确保 _currentIndex 在有效范围内
    if (_currentIndex < 0 || _currentIndex >= widget.items.length) {
      if (widget.items.isEmpty) {
        // 如果列表为空，返回上一页
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            Navigator.pop(context);
          }
        });
        return const Scaffold(
          body: Center(child: CircularProgressIndicator()),
        );
      }
      // 如果索引超出范围，重置为 0
      _currentIndex = 0;
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.items[_currentIndex].title.isNotEmpty
              ? widget.items[_currentIndex].title
              : '收藏详情',
          style: const TextStyle(fontSize: AppConstants.appBarTitleFontSize),
        ),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        actions: [
          PopupMenuButton<String>(
            onSelected: (value) {
              final item = widget.items[_currentIndex];
              final pageState = _getPageState(_currentIndex);

              if (value == 'edit') {
                _onEdit(context, item);
              } else if (value == 'delete') {
                _onDelete(context, item);
              } else if (value == 'favorite') {
                _onToggleFavorite(context, item);
              } else if (value == 'toggle_view') {
                setState(() {
                  pageState.showWebView = !pageState.showWebView;
                });
                // 更新 showType 到数据库
                // showType: 0=预览, 1=原文
                // showWebView: true=预览, false=原文
                final newShowType = pageState.showWebView ? 0 : 1;
                _updateShowType(item.id, newShowType);
              } else if (value.startsWith('style_')) {
                final styleIndex = int.parse(value.split('_')[1]);
                final newStyle = PreviewStyle.values[styleIndex];
                setState(() {
                  _globalPreviewStyle = newStyle;
                });
                _savePreviewStyle(newStyle);
              }
            },
            itemBuilder: (context) {
              final pageState = _getPageState(_currentIndex);
              final item = widget.items[_currentIndex];
              return [
                const PopupMenuItem(
                  value: 'edit',
                  child: Row(
                    children: [
                      Icon(Icons.edit),
                      SizedBox(width: 8),
                      Text('编辑'),
                    ],
                  ),
                ),
                PopupMenuItem(
                  value: 'favorite',
                  child: Row(
                    children: [
                      Icon(
                        item.isFavorite ? Icons.favorite : Icons.favorite_border,
                        color: item.isFavorite ? Colors.red : null,
                      ),
                      const SizedBox(width: 8),
                      Text(item.isFavorite ? '取消喜欢' : '喜欢'),
                    ],
                  ),
                ),
                PopupMenuItem(
                  value: 'toggle_view',
                  child: Row(
                    children: [
                      Icon(pageState.showWebView ? Icons.article : Icons.visibility),
                      const SizedBox(width: 8),
                      Text(pageState.showWebView ? '原文' : '预览'),
                    ],
                  ),
                ),
                const PopupMenuDivider(),
                const PopupMenuItem(
                  enabled: false,
                  child: Text(
                    '预览样式',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 12,
                    ),
                  ),
                ),
                ...PreviewStyle.values.asMap().entries.map((entry) {
                  final style = entry.value;
                  final isSelected = _globalPreviewStyle == style;
                  return PopupMenuItem(
                    value: 'style_${entry.key}',
                    child: Row(
                      children: [
                        SizedBox(
                          width: 20,
                          child: isSelected
                              ? const Icon(Icons.check, size: 16)
                              : null,
                        ),
                        const SizedBox(width: 8),
                        Expanded(child: Text(style.name)),
                      ],
                    ),
                  );
                }).toList(),
                const PopupMenuDivider(),
                const PopupMenuItem(
                  value: 'delete',
                  child: Row(
                    children: [
                      Icon(Icons.delete, color: Colors.red),
                      SizedBox(width: 8),
                      Text('删除', style: TextStyle(color: Colors.red)),
                    ],
                  ),
                ),
              ];
            },
          ),
        ],
      ),
      body: PageView.builder(
        controller: _pageController,
        scrollDirection: Axis.horizontal,
        itemCount: widget.items.length,
        onPageChanged: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        itemBuilder: (context, index) {
          final item = widget.items[index];
          final pageState = _getPageState(index);
          return _buildBody(item, pageState);
        },
      ),
    );
  }
}

// 页面状态类
class _PageState {
  String? extractedUrl;
  WebViewController? webViewController;
  bool isLoading;
  bool showWebView;

  _PageState({
    this.extractedUrl,
    this.webViewController,
    required this.isLoading,
    required this.showWebView,
  });
}

// 预览样式枚举
enum PreviewStyle {
  quote('引号式'),
  card('卡片式'),
  minimal('简约式'),
  bookmark('书签式'),
  gradient('渐变式');

  final String name;
  const PreviewStyle(this.name);
}
